from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.mail import send_mail

from .models import *
from .serializer import *
from django.contrib.auth.hashers import make_password,check_password
import re


# 角色增加
class RoleView(APIView):
    def post(self,request):
        # 获取网页提交数据
        name=request.data.get('name')

        # 获取数据库内容，用来判断角色是否存在
        roleobj=Role.objects.filter(name=name).first()

        if roleobj:
            return Response({'code':1001,'msg':'角色存在'})

        obj=RoleSerializer(data=request.data)
        if obj.is_valid():
            obj.save()
            return Response({'code': 1000, 'msg': '添加成功'})
        print(obj.errors)
        return Response({'code': 1002, 'msg': '添加失败'})


class RegisterView(APIView):
    def post(self,request):
        # 获取网页提交数据
        username=request.data.get('username')
        password1=request.data.get('password1')
        password2=request.data.get('password2')
        phone=request.data.get('phone')
        role_id=request.data.get('role')
        email=request.data.get('email')

        # 判断数据完整性
        if not all([username,password1,password2,phone,email,role_id]):
            return Response({'code':400,'msg':'数据不完整'})

        if not re.compile(r'1(3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8[0-9]|9[0-9])\d{8}$'):
            return Response({'code':400,'msg':'手机号不符合规范'})


        # 获取数据库中数据，用来判断用户是否存在
        userobj=User.objects.filter(username=username).first()

        # 判断用户
        if userobj:
            return Response({'code':1001,'msg':'用户已存在'})

        # 判断两次密码
        if password1==password2:
            # 反序列化添加
            userdata={
                'username':username,
                'password':make_password(password1),
                'phone':phone,
                'email':email,
                'role':role_id,
            }

            obj=UserSerializer(data=userdata)

            if obj.is_valid():
                obj.save()
                # 发邮件

                # 异步
                subject='美多商城会员注册'
                message=''
                from_email=''
                recipient_list=[]
                html_message=''
                send_mail(subject, message, from_email, recipient_list,
                          html_message=html_message)

                # 发手机验证码

                return Response({'code': 1000, 'msg': '注册成功'})
            print(obj.errors)
            return Response({'code': 1002, 'msg': '注册失败'})
        else:
            return Response({'code': 1003, 'msg': '两次密码不一致'})




